package com.jianhua.appmarket.module.service.system.impl;

import com.jianhua.appmarket.common.util.SnowflakeKeyUtil;
import com.jianhua.appmarket.module.dao.system.MenuDao;
import com.jianhua.appmarket.module.entity.system.Menu;
import com.jianhua.appmarket.module.model.system.DeptVO;
import com.jianhua.appmarket.module.model.system.MenuParam;
import com.jianhua.appmarket.module.model.system.MenuVO;
import com.jianhua.appmarket.module.model.system.UserVO;
import com.jianhua.appmarket.module.service.system.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class MenuService implements IMenuService {


    @Autowired
    private MenuDao menuDao;

    @Override
    public List<MenuVO> listAllMenus(UserVO user) {
        MenuParam param = new MenuParam();
        param.setUserId(user.getId() == 0L ? user.getId() : null);//超级管理员
        List<MenuVO> vos = menuDao.listByParam(param);
        return buildMenuTree(vos,0L);
    }

    @Override
    public List<MenuVO> listMenusByUserId(Long userId) {
        return buildMenuTree(menuDao.listByUserId(userId),0L);
    }

    @Override
    public List<MenuVO> listBranchByParentId(Long parentId,UserVO user) {
        MenuParam param = new MenuParam();
        param.setParentId(parentId);
        param.setUserId(user.getId() == 0L ? user.getId() : null);//超级管理员
        return menuDao.listByParam(param);
    }

    @Override
    public Boolean addOrEditMenu(Menu menu, UserVO user) {
        if(Objects.isNull(menu.getId())) {
            menu.setId(SnowflakeKeyUtil.generateId());
            menu.setCreateUser(user.getNickName());
            return menuDao.insert(menu) > 0;
        }else {
            return editMenu(menu,user);
        }
    }

    @Override
    public Boolean editMenu(Menu menu, UserVO user) {
        menu.setUpdateUser(user.getNickName());
        return menuDao.update(menu) > 0;
    }


    @Override
    public Boolean deleteMenu(Long menuId) {
        return menuDao.deleteById(menuId) > 0;
    }

    private List<MenuVO> buildMenuTree(List<MenuVO> menuList, Long parentId) {
        List<MenuVO> treeList = new ArrayList<>();
        menuList.forEach(menu -> {
            if (Objects.equals(parentId, menu.getParentId())) {
                menu.setChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }
        });
        return treeList;
    }
}
